/*
 * 这里是网络请求拦截器
 * Lamking
 * */
import wepy from 'wepy'
import interfaces from '../interfaces/index'
export default async function request(options) {
  wepy.showLoading({
    title: '加载数据...^_^',
    // image: '/images/warn.png',
    icon: 'loading',
    duration: 100000,
    mask: false
  })
  // 处理data
  options['data'] = Object.assign({}, options.data)
  // 插入token
  let userInfo = await wepy.getStorage({key: 'userInfo'})
  options['data']['token'] = userInfo.data.token
  let url = await wepy.getStorageSync('serverUrl')
  // 合并请求时所需的数据
  let newObj = Object.assign({}, options, {
    url: url + '/client/' + options.url,
    method: 'POST',
    header: {
      'content-type': 'application/x-www-form-urlencoded',
      'Cookie': 'JSESSIONID='+ wx.getStorageSync('_session') || ''
    },
  })
  // 处理传输的data
  for (let obj in newObj.data) {
    if (obj.indexOf('delDtm') === 0 || obj.indexOf('createDtm') === 0 || obj.indexOf('updateDtm') === 0) {
      delete newObj.data[obj]
    }
  }
  // console.log(newObj.data)
  let response = await wepy.request(newObj)
  // response是服务端返回的对象
  // console.log('response', response)
  // if (response.data.code === 200) {
  //   wepy.hideLoading()
  // } else {
  //   wepy.showToast({
  //     title: '系统异常^.^' + response.data.code,
  //     image: '/image/warn',
  //     duration: 4000,
  //     mask: true
  //   })
  // }
  return new Promise((resolve, reject) => {
    if (response.statusCode === 200 || response.statusCode === 777) {
      wepy.hideLoading()
      if (response.data.code === 200) {
        resolve(response)
      } else if (response.data.code === 444) {  // 未登录
        console.log('客户端掉线，尝试重新登录')
        try {
          interfaces.login()
        } catch (e) {
          wepy.showModal({
            title: '提示',
            content: `用户登录失败，请截图本提示，并联系客服。${e.message}`
          })
        }
      } else {
        wepy.showToast({
          title: response.data.msg,
          image: '/images/warn.png'
        })
        reject(response)
      }
    } else {
      wepy.showToast({
        title: response.data.msg,
        image: '/images/warn.png'
      })
      reject(response)
    }
  })
  // return response
}
